// 成就系统管理工具
import { getTestStats, getAllTestStats } from './testHistory.js'

/**
 * 检查并解锁成就
 * @param {string} testType - 测试类型
 * @param {object} testData - 测试数据
 * @returns {Array} 新解锁的成就列表
 */
export const checkAndUnlockAchievements = (testType, testData) => {
  try {
    const unlockedAchievements = []
    const currentAchievements = getAchievements()
    const testStats = getTestStats(testType)
    const allStats = getAllTestStats()
    
    // 检查各种成就条件
    const achievementChecks = [
      // 首次完成测试
      () => checkFirstTestAchievements(testType, testStats, currentAchievements),
      // 分数相关成就
      () => checkScoreAchievements(testType, testData, currentAchievements),
      // 连续测试成就
      () => checkStreakAchievements(testStats, currentAchievements),
      // 总体统计成就
      () => checkOverallAchievements(allStats, currentAchievements),
      // 特殊成就
      () => checkSpecialAchievements(testType, testData, testStats, currentAchievements)
    ]
    
    achievementChecks.forEach(checkFunction => {
      const newAchievements = checkFunction()
      if (newAchievements && newAchievements.length > 0) {
        unlockedAchievements.push(...newAchievements)
      }
    })
    
    // 保存解锁的成就
    if (unlockedAchievements.length > 0) {
      saveUnlockedAchievements(unlockedAchievements)
    }
    
    return unlockedAchievements
  } catch (error) {
    console.error('检查成就失败:', error)
    return []
  }
}

/**
 * 检查首次测试成就
 */
const checkFirstTestAchievements = (testType, testStats, currentAchievements) => {
  const unlockedAchievements = []
  
  const firstTestAchievements = {
    memory: 'memory_first',
    reaction: 'reaction_first',
    chimp: 'chimp_first',
    visual: 'visual_first',
    typing: 'typing_first'
  }
  
  const achievementId = firstTestAchievements[testType]
  if (achievementId && testStats.totalTests === 1 && !isAchievementUnlocked(achievementId, currentAchievements)) {
    unlockedAchievements.push({
      id: achievementId,
      name: `${getTestTypeName(testType)}初体验`,
      description: `完成第一次${getTestTypeName(testType)}测试`,
      icon: getTestTypeIcon(testType),
      rarity: 'common',
      unlockDate: new Date().toISOString()
    })
  }
  
  return unlockedAchievements
}

/**
 * 检查分数相关成就
 */
const checkScoreAchievements = (testType, testData, currentAchievements) => {
  const unlockedAchievements = []
  
  // 根据测试类型检查不同的分数成就
  switch (testType) {
    case 'memory':
      checkMemoryScoreAchievements(testData, currentAchievements, unlockedAchievements)
      break
    case 'reaction':
      checkReactionScoreAchievements(testData, currentAchievements, unlockedAchievements)
      break
    case 'chimp':
      checkChimpScoreAchievements(testData, currentAchievements, unlockedAchievements)
      break
    case 'visual':
      checkVisualScoreAchievements(testData, currentAchievements, unlockedAchievements)
      break
    case 'typing':
      checkTypingScoreAchievements(testData, currentAchievements, unlockedAchievements)
      break
  }
  
  return unlockedAchievements
}

/**
 * 检查记忆力测试分数成就
 */
const checkMemoryScoreAchievements = (testData, currentAchievements, unlockedAchievements) => {
  const scoreThresholds = [
    { score: 1000, id: 'memory_score_1000', name: '记忆新手', rarity: 'common' },
    { score: 5000, id: 'memory_score_5000', name: '记忆达人', rarity: 'rare' },
    { score: 10000, id: 'memory_score_10000', name: '记忆大师', rarity: 'epic' },
    { score: 20000, id: 'memory_score_20000', name: '记忆传奇', rarity: 'legendary' }
  ]
  
  scoreThresholds.forEach(threshold => {
    if (testData.finalScore >= threshold.score && !isAchievementUnlocked(threshold.id, currentAchievements)) {
      unlockedAchievements.push({
        id: threshold.id,
        name: threshold.name,
        description: `记忆力测试达到${threshold.score}分`,
        icon: '🧠',
        rarity: threshold.rarity,
        unlockDate: new Date().toISOString()
      })
    }
  })
  
  // 关卡成就
  const levelThresholds = [
    { level: 5, id: 'memory_level_5', name: '记忆探索者', rarity: 'common' },
    { level: 10, id: 'memory_level_10', name: '记忆挑战者', rarity: 'rare' },
    { level: 15, id: 'memory_level_15', name: '记忆征服者', rarity: 'epic' }
  ]
  
  levelThresholds.forEach(threshold => {
    if (testData.maxLevel >= threshold.level && !isAchievementUnlocked(threshold.id, currentAchievements)) {
      unlockedAchievements.push({
        id: threshold.id,
        name: threshold.name,
        description: `记忆力测试达到第${threshold.level}关`,
        icon: '🎯',
        rarity: threshold.rarity,
        unlockDate: new Date().toISOString()
      })
    }
  })
}

/**
 * 检查反应力测试成就
 */
const checkReactionScoreAchievements = (testData, currentAchievements, unlockedAchievements) => {
  const timeThresholds = [
    { time: 300, id: 'reaction_fast_300', name: '闪电反应', rarity: 'rare' },
    { time: 250, id: 'reaction_fast_250', name: '光速反应', rarity: 'epic' },
    { time: 200, id: 'reaction_fast_200', name: '超光速反应', rarity: 'legendary' }
  ]
  
  timeThresholds.forEach(threshold => {
    if (testData.averageTime <= threshold.time && !isAchievementUnlocked(threshold.id, currentAchievements)) {
      unlockedAchievements.push({
        id: threshold.id,
        name: threshold.name,
        description: `平均反应时间低于${threshold.time}ms`,
        icon: '⚡',
        rarity: threshold.rarity,
        unlockDate: new Date().toISOString()
      })
    }
  })
}

/**
 * 检查打字测试成就
 */
const checkTypingScoreAchievements = (testData, currentAchievements, unlockedAchievements) => {
  const wpmThresholds = [
    { wpm: 40, id: 'typing_wpm_40', name: '打字新手', rarity: 'common' },
    { wpm: 60, id: 'typing_wpm_60', name: '打字能手', rarity: 'rare' },
    { wpm: 80, id: 'typing_wpm_80', name: '打字高手', rarity: 'epic' },
    { wpm: 100, id: 'typing_wpm_100', name: '打字大师', rarity: 'legendary' }
  ]
  
  wpmThresholds.forEach(threshold => {
    if (testData.finalWPM >= threshold.wpm && !isAchievementUnlocked(threshold.id, currentAchievements)) {
      unlockedAchievements.push({
        id: threshold.id,
        name: threshold.name,
        description: `打字速度达到${threshold.wpm} WPM`,
        icon: '⌨️',
        rarity: threshold.rarity,
        unlockDate: new Date().toISOString()
      })
    }
  })
  
  // 准确率成就
  if (testData.finalAccuracy >= 0.95 && !isAchievementUnlocked('typing_accuracy_95', currentAchievements)) {
    unlockedAchievements.push({
      id: 'typing_accuracy_95',
      name: '精准打字',
      description: '打字准确率达到95%',
      icon: '🎯',
      rarity: 'rare',
      unlockDate: new Date().toISOString()
    })
  }
}

/**
 * 检查连续测试成就
 */
const checkStreakAchievements = (testStats, currentAchievements) => {
  const unlockedAchievements = []
  
  const streakThresholds = [
    { days: 3, id: 'streak_3', name: '坚持不懈', rarity: 'common' },
    { days: 7, id: 'streak_7', name: '一周挑战', rarity: 'rare' },
    { days: 30, id: 'streak_30', name: '月度坚持', rarity: 'epic' },
    { days: 100, id: 'streak_100', name: '百日坚持', rarity: 'legendary' }
  ]
  
  streakThresholds.forEach(threshold => {
    if (testStats.streak >= threshold.days && !isAchievementUnlocked(threshold.id, currentAchievements)) {
      unlockedAchievements.push({
        id: threshold.id,
        name: threshold.name,
        description: `连续${threshold.days}天进行测试`,
        icon: '🔥',
        rarity: threshold.rarity,
        unlockDate: new Date().toISOString()
      })
    }
  })
  
  return unlockedAchievements
}

/**
 * 检查总体统计成就
 */
const checkOverallAchievements = (allStats, currentAchievements) => {
  const unlockedAchievements = []
  
  // 总测试次数成就
  const testCountThresholds = [
    { count: 10, id: 'total_tests_10', name: '测试探索者', rarity: 'common' },
    { count: 50, id: 'total_tests_50', name: '测试爱好者', rarity: 'rare' },
    { count: 100, id: 'total_tests_100', name: '测试专家', rarity: 'epic' },
    { count: 500, id: 'total_tests_500', name: '测试大师', rarity: 'legendary' }
  ]
  
  testCountThresholds.forEach(threshold => {
    if (allStats.totalTests >= threshold.count && !isAchievementUnlocked(threshold.id, currentAchievements)) {
      unlockedAchievements.push({
        id: threshold.id,
        name: threshold.name,
        description: `完成${threshold.count}次测试`,
        icon: '📊',
        rarity: threshold.rarity,
        unlockDate: new Date().toISOString()
      })
    }
  })
  
  // 全能成就（完成所有类型测试）
  const completedTestTypes = Object.keys(allStats).filter(key => 
    ['memory', 'reaction', 'chimp', 'visual', 'typing'].includes(key) && allStats[key].totalTests > 0
  ).length
  
  if (completedTestTypes >= 5 && !isAchievementUnlocked('all_test_types', currentAchievements)) {
    unlockedAchievements.push({
      id: 'all_test_types',
      name: '全能挑战者',
      description: '完成所有类型的测试',
      icon: '🌟',
      rarity: 'epic',
      unlockDate: new Date().toISOString()
    })
  }
  
  return unlockedAchievements
}

/**
 * 检查特殊成就
 */
const checkSpecialAchievements = (testType, testData, testStats, currentAchievements) => {
  const unlockedAchievements = []
  
  // 完美表现成就
  if (testType === 'memory' && testData.grade === 'S' && !isAchievementUnlocked('memory_perfect', currentAchievements)) {
    unlockedAchievements.push({
      id: 'memory_perfect',
      name: '记忆完美',
      description: '记忆力测试获得S级评价',
      icon: '💎',
      rarity: 'legendary',
      unlockDate: new Date().toISOString()
    })
  }
  
  // 夜猫子成就（深夜测试）
  const currentHour = new Date().getHours()
  if ((currentHour >= 23 || currentHour <= 5) && !isAchievementUnlocked('night_owl', currentAchievements)) {
    unlockedAchievements.push({
      id: 'night_owl',
      name: '夜猫子',
      description: '在深夜进行测试',
      icon: '🦉',
      rarity: 'rare',
      unlockDate: new Date().toISOString()
    })
  }
  
  // 早起鸟成就（早晨测试）
  if (currentHour >= 5 && currentHour <= 8 && !isAchievementUnlocked('early_bird', currentAchievements)) {
    unlockedAchievements.push({
      id: 'early_bird',
      name: '早起鸟',
      description: '在早晨进行测试',
      icon: '🐦',
      rarity: 'rare',
      unlockDate: new Date().toISOString()
    })
  }
  
  return unlockedAchievements
}

/**
 * 检查成就是否已解锁
 */
const isAchievementUnlocked = (achievementId, currentAchievements) => {
  return currentAchievements.some(achievement => achievement.id === achievementId && achievement.unlocked)
}

/**
 * 获取当前成就列表
 */
const getAchievements = () => {
  try {
    const stored = uni.getStorageSync('user_achievements')
    return stored ? JSON.parse(stored) : []
  } catch (error) {
    console.error('获取成就列表失败:', error)
    return []
  }
}

/**
 * 保存解锁的成就
 */
const saveUnlockedAchievements = (newAchievements) => {
  try {
    const currentAchievements = getAchievements()
    
    newAchievements.forEach(newAchievement => {
      const existingIndex = currentAchievements.findIndex(a => a.id === newAchievement.id)
      if (existingIndex >= 0) {
        currentAchievements[existingIndex] = { ...newAchievement, unlocked: true }
      } else {
        currentAchievements.push({ ...newAchievement, unlocked: true })
      }
    })
    
    uni.setStorageSync('user_achievements', JSON.stringify(currentAchievements))
    
    // 触发成就解锁通知
    newAchievements.forEach(achievement => {
      showAchievementNotification(achievement)
    })
  } catch (error) {
    console.error('保存成就失败:', error)
  }
}

/**
 * 显示成就解锁通知
 */
const showAchievementNotification = (achievement) => {
  uni.showToast({
    title: `🎉 解锁成就：${achievement.name}`,
    icon: 'none',
    duration: 3000
  })
}

/**
 * 获取测试类型名称
 */
const getTestTypeName = (testType) => {
  const names = {
    memory: '记忆力',
    reaction: '反应力',
    chimp: '黑猩猩',
    visual: '视觉记忆',
    typing: '打字速度'
  }
  return names[testType] || testType
}

/**
 * 获取测试类型图标
 */
const getTestTypeIcon = (testType) => {
  const icons = {
    memory: '🧠',
    reaction: '⚡',
    chimp: '🐵',
    visual: '👁️',
    typing: '⌨️'
  }
  return icons[testType] || '🏆'
}

/**
 * 获取所有可用成就
 * @returns {Array} 成就列表
 */
export const getAllAvailableAchievements = () => {
  return [
    // 首次测试成就
    { id: 'memory_first', name: '记忆力初体验', description: '完成第一次记忆力测试', icon: '🧠', rarity: 'common' },
    { id: 'reaction_first', name: '反应力初体验', description: '完成第一次反应力测试', icon: '⚡', rarity: 'common' },
    { id: 'chimp_first', name: '黑猩猩初体验', description: '完成第一次黑猩猩测试', icon: '🐵', rarity: 'common' },
    { id: 'visual_first', name: '视觉记忆初体验', description: '完成第一次视觉记忆测试', icon: '👁️', rarity: 'common' },
    { id: 'typing_first', name: '打字速度初体验', description: '完成第一次打字速度测试', icon: '⌨️', rarity: 'common' },
    
    // 分数成就
    { id: 'memory_score_1000', name: '记忆新手', description: '记忆力测试达到1000分', icon: '🧠', rarity: 'common' },
    { id: 'memory_score_5000', name: '记忆达人', description: '记忆力测试达到5000分', icon: '🧠', rarity: 'rare' },
    { id: 'memory_score_10000', name: '记忆大师', description: '记忆力测试达到10000分', icon: '🧠', rarity: 'epic' },
    { id: 'memory_score_20000', name: '记忆传奇', description: '记忆力测试达到20000分', icon: '🧠', rarity: 'legendary' },
    
    // 反应力成就
    { id: 'reaction_fast_300', name: '闪电反应', description: '平均反应时间低于300ms', icon: '⚡', rarity: 'rare' },
    { id: 'reaction_fast_250', name: '光速反应', description: '平均反应时间低于250ms', icon: '⚡', rarity: 'epic' },
    { id: 'reaction_fast_200', name: '超光速反应', description: '平均反应时间低于200ms', icon: '⚡', rarity: 'legendary' },
    
    // 打字成就
    { id: 'typing_wpm_40', name: '打字新手', description: '打字速度达到40 WPM', icon: '⌨️', rarity: 'common' },
    { id: 'typing_wpm_60', name: '打字能手', description: '打字速度达到60 WPM', icon: '⌨️', rarity: 'rare' },
    { id: 'typing_wpm_80', name: '打字高手', description: '打字速度达到80 WPM', icon: '⌨️', rarity: 'epic' },
    { id: 'typing_wpm_100', name: '打字大师', description: '打字速度达到100 WPM', icon: '⌨️', rarity: 'legendary' },
    { id: 'typing_accuracy_95', name: '精准打字', description: '打字准确率达到95%', icon: '🎯', rarity: 'rare' },
    
    // 连续测试成就
    { id: 'streak_3', name: '坚持不懈', description: '连续3天进行测试', icon: '🔥', rarity: 'common' },
    { id: 'streak_7', name: '一周挑战', description: '连续7天进行测试', icon: '🔥', rarity: 'rare' },
    { id: 'streak_30', name: '月度坚持', description: '连续30天进行测试', icon: '🔥', rarity: 'epic' },
    { id: 'streak_100', name: '百日坚持', description: '连续100天进行测试', icon: '🔥', rarity: 'legendary' },
    
    // 总体成就
    { id: 'total_tests_10', name: '测试探索者', description: '完成10次测试', icon: '📊', rarity: 'common' },
    { id: 'total_tests_50', name: '测试爱好者', description: '完成50次测试', icon: '📊', rarity: 'rare' },
    { id: 'total_tests_100', name: '测试专家', description: '完成100次测试', icon: '📊', rarity: 'epic' },
    { id: 'total_tests_500', name: '测试大师', description: '完成500次测试', icon: '📊', rarity: 'legendary' },
    { id: 'all_test_types', name: '全能挑战者', description: '完成所有类型的测试', icon: '🌟', rarity: 'epic' },
    
    // 特殊成就
    { id: 'memory_perfect', name: '记忆完美', description: '记忆力测试获得S级评价', icon: '💎', rarity: 'legendary' },
    { id: 'night_owl', name: '夜猫子', description: '在深夜进行测试', icon: '🦉', rarity: 'rare' },
    { id: 'early_bird', name: '早起鸟', description: '在早晨进行测试', icon: '🐦', rarity: 'rare' }
  ]
}